﻿using System;
using System.Linq;
using System.Messaging;
using System.Threading;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Text.RegularExpressions;

namespace PSE.Communication.Fix.Common
{
    public class FileRepository
    {
        private string _directoryName;
        private string _fileName;
        private int _count;

        public int Count
        {
            get { return _count; }
            set { _count = value; }
        }

        public FileRepository(string directoryName)
        {
            _directoryName = directoryName;
            _fileName = "FixBackupMessages_";
            _count = GetLastCountFile();

            if (!Directory.Exists(_directoryName))
                Directory.CreateDirectory(_directoryName);
        }

        /// <summary>
        /// Atualizar os dados de um arquivo pre-existente
        /// </summary>
        /// <param name="parameters"></param>
        public void UpdateData(RepositoryParameter[] parameters)
        {
            string fileName = GetFirstFile();
            using (StreamWriter w = new StreamWriter(fileName, false))
            {
                foreach (RepositoryParameter item in parameters)
                {
                    w.WriteLine(item.ToString());
                }
            }
        }

        public void SaveData(RepositoryParameter[] parameters)
        {
            using (StreamWriter w = new StreamWriter(Path.Combine(_directoryName, _fileName + (_count + 1).ToString() + ".txt")))
            {
                foreach (RepositoryParameter item in parameters)
                {
                    w.WriteLine(item.ToString());
                }
            }

            _count++;
        }

        public RepositoryParameter[] GetData()
        {
            string fileName = GetFirstFile();
            List<RepositoryParameter> parameters = new List<RepositoryParameter>(); ;

            if (!string.IsNullOrEmpty(fileName))
            {
                using (StreamReader reader = new StreamReader(fileName))
                {
                    string line = reader.ReadLine();

                    while (line != null)
                    {
                        RepositoryParameter parameter = new RepositoryParameter();
                        //string[] parts = line.Split('\t');
                        string[] parts = Regex.Split(line, RepositoryParameter.FIELD_SEPARATOR);

                        if (parts.Length == 5)//se tiver as primeira 5 posicoes, recuperar os dados armazenados em arquivo
                        {
                            parameter.Id = Convert.ToInt32(parts[0]);
                            parameter.CompanyId = Convert.ToInt32(parts[1]);
                            parameter.ReceiveDate = Convert.ToDateTime(parts[2]);
                            parameter.MessageType = parts[3];
                            parameter.Message = parts[4];

                            parameters.Add(parameter);
                        }

                        line = reader.ReadLine();
                    }
                }
            }

            return parameters.ToArray();
        }

        public void DeleteFile()
        {
            string fileName = GetFirstFile();

            if (!string.IsNullOrEmpty(fileName))
            {
                _count--;
                File.Delete(fileName);
            }
        }

        protected IOrderedEnumerable<FileInfo> GetFiles()
        {
            List<FileInfo> files = new List<FileInfo>();

            foreach (string item in Directory.GetFiles(_directoryName, _fileName + "*.txt"))
            {
                files.Add(new FileInfo(item));
            }

            return files.OrderBy(x => x.CreationTime);
        }

        protected string GetFirstFile()
        {
            string fileName = string.Empty;

            IOrderedEnumerable<FileInfo> result = GetFiles();

            if (result.Count() > 0)
                fileName = result.First().FullName;

            return fileName;
        }

        protected int GetLastCountFile()
        {
            int count = 0;

            IOrderedEnumerable<FileInfo> result = GetFiles();

            if (result.Count() > 0)
            {
                count = Convert.ToInt32(Path.GetFileNameWithoutExtension(result.Last().Name).Replace(_fileName, string.Empty));
            }

            return count;
        }
    }
}